﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Linq;
using System.Data;
using System.Data.SqlClient;

namespace MODULE_KETOAN
{
    public partial class frm_thanhtoantienhang : Form
    {
        int trangthai;//1 phieu moi,0 la phieu cu
        ketoanDataContext context = cls_ketoan.getcontext();
        int currenrowindex;
        public frm_thanhtoantienhang()
        {
            InitializeComponent();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            double tongtienhang = double.Parse(txtongtienhang.Text.ToString());
            double VAT = double.Parse(this.txtVAT.Text);
            double thanhtoan = double.Parse(this.txtthanhtoan.Text);
            thanhtoan = tongtienhang - VAT;
            this.txtthanhtoan.Text = thanhtoan.ToString();
        }
        private void getdanhsachphieuchuathanhtoancuachuhang()
        {
            string machuhang = this.txtmachuhang.Text;
            this.grdata.Rows.Clear();

            ISingleResult<KT_getdanhsachphieuchuathanhtoanResult> result = context.KT_getdanhsachphieuchuathanhtoan(machuhang);
            List<KT_getdanhsachphieuchuathanhtoanResult> list = new List<KT_getdanhsachphieuchuathanhtoanResult>();
            if (result != null)
            {
                list = result.ToList();
            }
            if (list.Count() > 0)
            {
                double tongtienhang = 0;
                for (int i = 0; i < list.Count(); i++)
                {
                    KT_getdanhsachphieuchuathanhtoanResult element = list.ElementAt(i);
                    this.grdata.Rows.Add();
                    this.grdata.Columns["check"].ReadOnly = false;
                    this.grdata.Rows[i].Cells["check"].Value = false;
                    this.grdata.Rows[i].Cells["sophieu"].Value = element.sophieu;
                    this.grdata.Rows[i].Cells["ngaynhap"].Value = element.giovao;
                    this.grdata.Rows[i].Cells["xecho"].Value = element.soxe = element.soxe;
                    this.grdata.Rows[i].Cells["noidung"].Value = element.noidung;
                    this.grdata.Rows[i].Cells["thanhtien"].Value = element.thanhtien;
                    //if (element.thanhtien != null)
                    //{
                    //    tongtienhang += (double)element.thanhtien;
                    //}
                }
                this.txtongtienhang.Text = tongtienhang.ToString();
                this.txtVAT.Text = "0";
                this.txtthanhtoan.Text = tongtienhang.ToString();

            }

        }

        private void txtmachuhang_KeyDown(object sender, KeyEventArgs e)
        {
            
          
               
                    
                    if (e.KeyCode == Keys.Enter)
                    {
                        string machuhang = this.txtmachuhang.Text;
                        if (machuhang != "")
                        {
                            IEnumerable<DM_chuhang> chuhangs = from c in context.DM_chuhangs where c.machuhang.Equals(machuhang) select c;
                            if (chuhangs.Count() > 0)
                            {
                                DM_chuhang chuhang = chuhangs.ElementAt(0);
                                this.txttenchuhang.Text = chuhang.tenchuhang;
                                this.txtdiachi.Text = chuhang.diachi;

                            }
                            else
                            {
                                MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                                cls.ShowForm("frm_timkiemchuhang");
                                this.txtmachuhang.Text = cls._makhachhang;
                                chuhangs = from c in context.DM_chuhangs where c.machuhang.Equals(this.txtmachuhang.Text) select c;
                                if (chuhangs.Count() > 0)
                                {
                                    DM_chuhang chuhang = chuhangs.ElementAt(0);
                                    this.txttenchuhang.Text = chuhang.tenchuhang;
                                    this.txtdiachi.Text = chuhang.diachi;
                                }
                            }
                        }
                        else
                        {

                            MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                            cls.ShowForm("frm_timkiemchuhang");
                            this.txtmachuhang.Text = cls._makhachhang;
                            IEnumerable<DM_chuhang> chuhangs = from c in context.DM_chuhangs where c.machuhang.Equals(this.txtmachuhang.Text) select c;
                            if (chuhangs.Count() > 0)
                            {
                                DM_chuhang chuhang = chuhangs.ElementAt(0);
                                this.txttenchuhang.Text = chuhang.tenchuhang;
                                this.txtdiachi.Text = chuhang.diachi;
                            }
                        }

                        /////////////lay thong tin cac phieu nhap cua chu hang

                        getdanhsachphieuchuathanhtoancuachuhang();



                    }
               
              
               
                
          
        }
        private void loaddanhsachhoadontheongay()
        {
            string tungay, denngay;
            string d, m, y;

            if (this.dtptungay.Value.Day >= 10)
            {
                d = this.dtptungay.Value.Day.ToString();
            }
            else
            {
                d = "0" + this.dtptungay.Value.Day.ToString();
            }

            if (this.dtptungay.Value.Month >= 10)
            {
                m = this.dtptungay.Value.Month.ToString();
            }
            else
            {
                m = "0" + this.dtptungay.Value.Month.ToString();
            }
            y = this.dtptungay.Value.Year.ToString();
            tungay = d + "/" + m + "/" + y;
            if (this.dtpdenngay.Value.Day >= 10)
            {
                d = this.dtpdenngay.Value.Day.ToString();
            }
            else
            {
                d = "0" + this.dtpdenngay.Value.Day.ToString();
            }

            if (this.dtpdenngay.Value.Month >= 10)
            {
                m = this.dtpdenngay.Value.Month.ToString();
            }
            else
            {
                m = "0" + this.dtpdenngay.Value.Month.ToString();
            }
            y = this.dtpdenngay.Value.Year.ToString();
            denngay = d + "/" + m + "/" + y;

            List<KT_danhsachhoadontheongayResult> hoadons = context.KT_danhsachhoadontheongay(tungay,denngay).ToList<KT_danhsachhoadontheongayResult>();
            grdanhsach.Rows.Clear();
            if (hoadons.Count() > 0)
            {
                for (int i = 0; i < hoadons.Count(); i++)
                {
                    grdanhsach.Rows.Add();
                    KT_danhsachhoadontheongayResult hoadon = hoadons.ElementAt(i);
                    if (hoadon.sohoadon != null)
                    {
                        grdanhsach.Rows[i].Cells["sohoadon"].Value = hoadon.sohoadon;
                    }
                    if (hoadon.ngayhoadon != null)
                    {
                        grdanhsach.Rows[i].Cells["ngay"].Value = hoadon.ngayhoadon;
                    }
                    if (hoadon.tenchuhang != null)
                    {
                        grdanhsach.Rows[i].Cells["khachhang"].Value = hoadon.tenchuhang;
                    }
                    else
                    {
                        grdanhsach.Rows[i].Cells["khachhang"].Value = "";
                    }
                    if (hoadon.diachi != null)
                    {
                        grdanhsach.Rows[i].Cells["diachi"].Value = hoadon.diachi;
                    }
                    if (hoadon.thanhtoanbangso != null)
                    {
                        grdanhsach.Rows[i].Cells["sotien"].Value = hoadon.thanhtoanbangso;
                    }
                    else
                    {
                        grdanhsach.Rows[i].Cells["sotien"].Value = 0;

                    }
                    if (hoadon.TenCongTy != null)
                    {
                        grdanhsach.Rows[i].Cells["congty"].Value = hoadon.TenCongTy;
                    }

                }
            }
        }

        private void load()
        {
            trangthai = 1;
            string sophieu = context.P_getsohoadonchi().ToList().ElementAt(0).sophieu;
            this.txtsophieu.Text = sophieu;
            loaddanhsachhoadontheongay();
        }
        private void frm_thanhtoantienhang_Load(object sender, EventArgs e)
        {
            try
            {
            

                trangthai = 1;
                
                this.cbcongty.DataSource = context.DM_CongTies.AsEnumerable();
                this.cbcongty.DisplayMember = "TenCongTy";
                this.cbcongty.ValueMember = "MaCongTy";
                load();
            
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi:" + ex.Message);
            }
        }

        private Boolean formvalidate()
        {
            bool kq = true;
            if (this.txtmachuhang.Text == "")
            {
                kq = false;
            }
            else
            {
                string machuhang = txtmachuhang.Text;
                IEnumerable<DM_chuhang> chuhangs = from c in context.DM_chuhangs where c.machuhang.Equals(machuhang) select c;
                if (chuhangs.Count() <= 0)
                {
                    kq = false;
                }
            }
            return kq;
        }
        private void btSave_Click(object sender, EventArgs e)
        {

            if (formvalidate() == true)
            {
               



               
               
                cls_chuyensothanhchu ntos=new cls_chuyensothanhchu();
                try
                {
                    KT_hoadon_h h = new KT_hoadon_h();
                    h.sohoadon = this.txtsophieu.Text;
                    h.machuhang = txtmachuhang.Text;
                    h.macongty = cbcongty.SelectedValue.ToString();
                    
                    string d, m, y;
                    string ngayhoadon;
                    if (this.dtpngay.Value.Day >= 10)
                    {
                        d = this.dtpngay.Value.Day.ToString();
                    }
                    else
                    {
                        d = "0" + this.dtpngay.Value.Day.ToString();
                    }

                    if (this.dtpngay.Value.Month >= 10)
                    {
                        m = this.dtpngay.Value.Month.ToString();
                    }
                    else
                    {
                        m = "0" + this.dtpngay.Value.Month.ToString();
                    }
                    y = this.dtpngay.Value.Year.ToString();
                    ngayhoadon = d + "/" + m + "/" + y;
                    h.ngayhoadon = ngayhoadon;

                    h.tongcongbangso = long.Parse(this.txtongtienhang.Text.ToString());
                    h.tongcongbangchu = ntos.DocSoThanhChu(long.Parse(this.txtongtienhang.Text.ToString())) +" đồng";
                    h.thanhtoanbangso = long.Parse(txtthanhtoan.Text.ToString());
                    h.thanhtoanbangchu=ntos.DocSoThanhChu(long.Parse(txtthanhtoan.Text.ToString())) +" đồng";
                    h.VATbangso = long.Parse(this.txtVAT.Text.ToString());
                    h.VATbangchu=ntos.DocSoThanhChu(long.Parse(this.txtVAT.Text.ToString()))+ "đồng";
                    context.KT_hoadon_hs.InsertOnSubmit(h);
                    context.SubmitChanges();
                     KT_hoadon_l l;
                    for (int i = 0; i < this.grdata.RowCount; i++)
                    {
                        if ((bool)this.grdata.Rows[i].Cells["check"].Value== true && this.grdata.Rows[i].Cells["sophieu"].Value != null)
                        {
                            l= new KT_hoadon_l();
                            if (context.KT_hoadon_ls.Count() > 0)
                            {
                                var id = (from c in context.KT_hoadon_ls select c.id_hoadon_l).Max() + 1;
                                l.id_hoadon_l = id;
                            }
                            else
                            {
                                l.id_hoadon_l = 1;
                            }
                            l.KT_hoadon_h = h;
                            if (grdata.Rows[i].Cells["noidung"].Value != null)
                            {
                                l.noidung = grdata.Rows[i].Cells["noidung"].Value.ToString();
                            }
                            l.sohoadon = h.sohoadon;
                            if (grdata.Rows[i].Cells["sophieu"].Value != null)
                            {
                                l.sophieunhap = grdata.Rows[i].Cells["sophieu"].Value.ToString();
                            }
                            if (grdata.Rows[i].Cells["thanhtien"].Value != null)
                            {
                                l.thanhtien = double.Parse(grdata.Rows[i].Cells["thanhtien"].Value.ToString());
                            }
                           

                            context.KT_hoadon_ls.InsertOnSubmit(l);
                           
                        }
                        context.SubmitChanges();
                    }
                    
                        MessageBox.Show("Lưu thành công", "Thông báo", MessageBoxButtons.OK);
                        getdanhsachphieuchuathanhtoancuachuhang();    
                        load();
                        btSave.Enabled = false;
                    
                }

                catch (Exception ex)
                {
                    MessageBox.Show("Không lưu được.Lỗi:" + ex.Message);
                    btSave.Enabled = true;
                }
            }
           

        }
       

        private void loadthongtinhoadon()
        {
            string sophieu = this.txtsophieu.Text;
           IEnumerable<KT_hoadon_h> hs=from c in context.KT_hoadon_hs where c.sohoadon.Equals(sophieu) select c;
           if(hs.Count()>0)
           {
               trangthai = 0;
               
               this.txtmachuhang.ReadOnly = true;

               KT_hoadon_h h = hs.ElementAt(0);
               this.txtmachuhang.Text = h.machuhang;
               this.txtongtienhang.Text = h.tongcongbangso.ToString();
               this.txtVAT.Text = h.VATbangso.ToString();
               this.txtthanhtoan.Text = h.thanhtoanbangso.ToString();

               IEnumerable<DM_chuhang> chuhangs = from c in context.DM_chuhangs where c.machuhang.Equals(h.machuhang) select c;
               if (chuhangs.Count() > 0)
               {
                   DM_chuhang chuhang = chuhangs.ElementAt(0);
                   this.txttenchuhang.Text = chuhang.tenchuhang;
                   this.txtdiachi.Text = chuhang.diachi;
                 
                   
               }
               this.dtpngay.Value = DateTime.Parse(h.ngayhoadon);
               this.cbcongty.SelectedValue = h.macongty;
               IEnumerable<KT_hoadon_l> ls = from c in context.KT_hoadon_ls where c.sohoadon.Equals(h.sohoadon) select c;


              // KT_hoadon_l ls=from c in context.KT_hoadon_ls where c.sohoadon.Equals
               grdata.Rows.Clear();
               for (int i = 0; i < ls.Count(); i++)
               {
                   KT_hoadon_l l = ls.ElementAt(i);
                   grdata.Rows.Add();
                   if (l.sophieunhap != null)
                   {
                       grdata.Rows[i].Cells["sophieu"].Value = l.sophieunhap;
                   }
                   else
                   {
                      // grdata.Rows[i].Cells["sophieu"].Value = l.sohoadon;
                   }
                   
                  IEnumerable<NX_phieunhaphang_h> phieunhaphanghs=from c in context.NX_phieunhaphang_hs where c.sophieu.Equals(l.sophieunhap)select c;
                  if (phieunhaphanghs.Count() > 0)
                  {
                      NX_phieunhaphang_h phieunhaphangh= phieunhaphanghs.ElementAt(0);
                      if (phieunhaphangh.giovao != null)
                      {
                          grdata.Rows[i].Cells["ngaynhap"].Value = phieunhaphangh.giovao;
                      }
                      else
                      {
                          grdata.Rows[i].Cells["ngaynhap"].Value = "";
                      }
                      if (phieunhaphangh.soxe != null)
                      {
                          grdata.Rows[i].Cells["xecho"].Value = phieunhaphangh.soxe;
                      }
                   

                      
                  }
                   
                   

                   
                   grdata.Rows[i].Cells["noidung"].Value = l.noidung;
                   grdata.Rows[i].Cells["thanhtien"].Value =l.thanhtien;



                   
               }

           }
 
        }
        private void txtsophieu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string sophieu = this.txtsophieu.Text;
                IEnumerable<KT_hoadon_h> hs = from c in context.KT_hoadon_hs where c.sohoadon.Equals(sophieu) select c;
                if (hs.Count() > 0)
                {
                    loadthongtinhoadon();
                }
            }
        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            btAdd.Enabled = true;
            this.btSave.Enabled = true;
            trangthai = 1;
            this.txtmachuhang.ReadOnly = false;
            string sophieu = context.P_getsohoadonchi().ToList().ElementAt(0).sophieu;
            this.txtsophieu.Text = sophieu;
            this.grdata.Rows.Clear();
            this.txtmachuhang.Text = "Enter để tìm";
            this.txtmachuhang.ReadOnly = false;
            this.txttenchuhang.Text = "";
            this.txtdiachi.Text = "";
            this.txtongtienhang.Text = "0";
            this.txtthanhtoan.Text = "0";
            this.txtVAT.Text = "0";
            DateTime serverdate = context.p_getdate().ElementAt(0).serverdatetime;
            this.dtpngay.Value = serverdate;
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            try
            {
                string sohoadon = this.txtsophieu.Text;
                IEnumerable<KT_hoadon_l> hoadonls = from c in context.KT_hoadon_ls where c.sohoadon.Equals(sohoadon) select c;
                foreach (KT_hoadon_l hoadonl in hoadonls)
                {
                    context.KT_hoadon_ls.DeleteOnSubmit(hoadonl);
                }
                context.SubmitChanges();
                IEnumerable<KT_hoadon_h> hoadons = from c in context.KT_hoadon_hs where c.sohoadon.Equals(sohoadon) select c;
                foreach (KT_hoadon_h hoadon in hoadons)
                {
                    context.KT_hoadon_hs.DeleteOnSubmit(hoadon);
                }
                context.SubmitChanges();
                MessageBox.Show("Xóa thành công");
                loaddanhsachhoadontheongay();
                
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }
        private void getrowdata()
        {

            string sohoadon = this.grdanhsach.Rows[currenrowindex].Cells["sohoadon"].Value.ToString();
            IEnumerable<KT_hoadon_h> hoadonhs=from c in context.KT_hoadon_hs where c.sohoadon.Equals(sohoadon) select c;
            if (hoadonhs.Count() > 0)
            {   
                KT_hoadon_h hoadonh = hoadonhs.ElementAt(0);
                if (hoadonh.sohoadon != null)
                {
                    this.txtsophieu.Text = hoadonh.sohoadon;
                }
                if (hoadonh.machuhang != null)
                {
                    this.txtmachuhang.Text=hoadonh.machuhang;
                    if (hoadonh.DM_chuhang.tenchuhang != null)
                    {
                        this.txttenchuhang.Text = hoadonh.DM_chuhang.tenchuhang;
                        this.txtdiachi.Text = hoadonh.DM_chuhang.diachi;
                    }
                }
                if (hoadonh.DM_CongTy != null)
                {
                    this.cbcongty.SelectedValue = hoadonh.macongty;
                }
                txtmachuhang.ReadOnly = true;
                this.txtongtienhang.Text = hoadonh.tongcongbangso.ToString();
                this.txtVAT.Text = hoadonh.VATbangso.ToString();
                this.txtthanhtoan.Text = hoadonh.thanhtoanbangso.ToString();
                IEnumerable<KT_hoadon_l> hoadonls = from c in context.KT_hoadon_ls where c.sohoadon.Equals(sohoadon) select c;
                if (hoadonls.Count() > 0)
                {
                    
                    this.grdata.Rows.Clear();
                    for (int i = 0; i < hoadonls.Count(); i++)
                    {
                        grdata.Rows.Add();
                        
                        KT_hoadon_l hoadonl = hoadonls.ElementAt(i);
                        if (hoadonl.NX_phieunhaphang_h != null)
                        {
                            this.grdata.Rows[i].Cells["check"].ReadOnly = true;
                            this.grdata.Rows[i].Cells["check"].Value = true;
                            
                            this.grdata.Rows[i].Cells["sophieu"].Value = hoadonl.sophieunhap;
                            this.grdata.Rows[i].Cells["ngaynhap"].Value = hoadonl.NX_phieunhaphang_h.giovao;
                            this.grdata.Rows[i].Cells["xecho"].Value = hoadonl.NX_phieunhaphang_h.soxe;
                            this.grdata.Rows[i].Cells["noidung"].Value = hoadonl.noidung;
                            this.grdata.Rows[i].Cells["thanhtien"].Value = hoadonl.thanhtien;

                        }
                    }
                   // this.grdata.Columns["check"].ReadOnly = true;
                }
            }



        }
        private void grdanhsach_Click(object sender, EventArgs e)
        {
            try
            {

                currenrowindex = this.grdanhsach.CurrentRow.Index;
                this.grdanhsach.Rows[currenrowindex].Selected = true;
                getrowdata();
                this.btSave.Enabled = false;
                

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btNext_Click(object sender, EventArgs e)
        {
            try
            {
                if (grdanhsach.Rows.Count > 0)
                {
                    this.grdanhsach.Rows[currenrowindex].Selected = false;
                    if (currenrowindex < this.grdanhsach.Rows.Count - 1)
                    {
                        currenrowindex = currenrowindex + 1;
                    }

                    this.grdanhsach.Rows[currenrowindex].Selected = true;

                    getrowdata();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btLast_Click(object sender, EventArgs e)
        {
            try
            {
                if (grdanhsach.Rows.Count > 0)
                {
                    this.grdanhsach.Rows[currenrowindex].Selected = false;

                    currenrowindex = this.grdanhsach.Rows.Count - 1;


                    this.grdanhsach.Rows[currenrowindex].Selected = true;

                    getrowdata();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void btPrev_Click(object sender, EventArgs e)
        {
            try
            {
                if (grdanhsach.Rows.Count > 0)
                {
                    this.grdanhsach.Rows[currenrowindex].Selected = false;
                    if (currenrowindex > 0)
                    {
                        currenrowindex = currenrowindex - 1;
                    }

                    this.grdanhsach.Rows[currenrowindex].Selected = true;

                    getrowdata();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

            }
        }

        private void btFirst_Click(object sender, EventArgs e)
        {
            try
            {
                if (grdanhsach.Rows.Count > 0)
                {
                    this.grdanhsach.Rows[currenrowindex].Selected = false;

                    currenrowindex = 0;


                    this.grdanhsach.Rows[currenrowindex].Selected = true;

                    getrowdata();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private void btExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtkeyword_TextChanged(object sender, EventArgs e)
        {
            this.tabControl1.SelectedIndex = 1;
            string keyword = txtkeyword.Text;
            IEnumerable<KT_hoadon_h> hoadons = from c in context.KT_hoadon_hs where c.DM_chuhang.tenchuhang.Contains(keyword) select c;
            grdanhsach.Rows.Clear();
            if (hoadons.Count() > 0)
            {
                for (int i = 0; i < hoadons.Count(); i++)
                {
                    grdanhsach.Rows.Add();
                    KT_hoadon_h hoadon = hoadons.ElementAt(i);
                    if (hoadon.sohoadon != null)
                    {
                        grdanhsach.Rows[i].Cells["sohoadon"].Value = hoadon.sohoadon;
                    }
                    if (hoadon.ngayhoadon != null)
                    {
                        grdanhsach.Rows[i].Cells["ngay"].Value = hoadon.ngayhoadon;
                    }
                    if (hoadon.DM_chuhang.tenchuhang != null)
                    {
                        grdanhsach.Rows[i].Cells["khachhang"].Value = hoadon.DM_chuhang.tenchuhang;
                    }
                    else
                    {
                        grdanhsach.Rows[i].Cells["khachhang"].Value = "";
                    }
                    if (hoadon.DM_chuhang.diachi != null)
                    {
                        grdanhsach.Rows[i].Cells["diachi"].Value = hoadon.DM_chuhang.diachi;
                    }
                    if (hoadon.thanhtoanbangso != null)
                    {
                        grdanhsach.Rows[i].Cells["sotien"].Value = hoadon.thanhtoanbangso;
                    }
                    else
                    {
                        grdanhsach.Rows[i].Cells["sotien"].Value = 0;

                    }
                    if (hoadon.DM_CongTy.TenCongTy != null)
                    {
                        grdanhsach.Rows[i].Cells["congty"].Value = hoadon.DM_CongTy.TenCongTy;
                    }

                }
            }
            
        }

        private void grdata_Click(object sender, EventArgs e)
        {
            
        }

        private void grdata_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                String SoPhieu = txtsophieu.Text;
                IEnumerable<KT_hoadon_h> hoadonhs = from c in context.KT_hoadon_hs where c.sohoadon.Equals(SoPhieu) select c;
                if (hoadonhs.Count() <= 0) // Phieu chua luu.
                {
                    double tongthanhtien = double.Parse(txtongtienhang.Text);
                    if (e.ColumnIndex == 0 && e.RowIndex>=0)
                    {
                        if ((bool)grdata.Rows[e.RowIndex].Cells["check"].Value == false)
                        {
                            if (grdata.Rows[e.RowIndex].Cells["thanhtien"].Value != null)
                            {
                                tongthanhtien = tongthanhtien + double.Parse(grdata.Rows[e.RowIndex].Cells["thanhtien"].Value.ToString());
                            }
                            this.grdata.Rows[e.RowIndex].Cells["check"].Value = true;
                        }
                        else
                        {
                            if (grdata.Rows[e.RowIndex].Cells["thanhtien"].Value != null)
                            {
                                tongthanhtien = tongthanhtien - double.Parse(grdata.Rows[e.RowIndex].Cells["thanhtien"].Value.ToString());
                            }

                            this.grdata.Rows[e.RowIndex].Cells["check"].Value = false;
                        }

                    }

                    this.txtongtienhang.Text = tongthanhtien.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi:"+ex.Message);
            }
        }

        private void txtongtienhang_TextChanged(object sender, EventArgs e)
        {
            double tongtienhang = double.Parse(txtongtienhang.Text.ToString());
            double VAT=double.Parse(this.txtVAT.Text);
            double thanhtoan = double.Parse(this.txtthanhtoan.Text);
            thanhtoan = tongtienhang - VAT;
            this.txtthanhtoan.Text = thanhtoan.ToString();
        }

        private void txtmachuhang_TextChanged(object sender, EventArgs e)
        {

        }

        private void btPrint_Click(object sender, EventArgs e)
        {
            string sophieu = this.txtsophieu.Text;

            try
            {
                String macongty = this.cbcongty.SelectedValue.ToString();

                //IEnumerable<KT_hoadon_h> hoadon_hs = from c in context.KT_hoadon_hs where c.sohoadon.Equals(sophieu) select c;
                DataSet ds = new DataSet();
                string connectstring = context.Connection.ConnectionString;
                SqlConnection connection = new SqlConnection(connectstring);
                SqlCommand command = new SqlCommand();
                command.Connection = connection;
                command.CommandText = "select * from hoadonthanhtoan_h where sophieu='"+sophieu+"'";

                SqlDataAdapter adapter = new SqlDataAdapter(command);
                DataTable tb = new DataTable("hoadon_h");
                adapter.Fill(tb);
                ds.Tables.Add(tb);
                command.CommandText = "select * from hoadonthanhtoan_l where sohoadon='"+sophieu+"'";
                DataTable tbl = new DataTable("hoadon_l");
                adapter.Fill(tbl);
                ds.Tables.Add(tbl);

                MODULE_TIENICH.cls_report objReport = new MODULE_TIENICH.cls_report();
                MODULE_TIENICH.cls_tienich cls = new MODULE_TIENICH.cls_tienich();
                //DataTable dt = cls.IEnumerabletoDataTable(lst);
                Cursor.Current = Cursors.WaitCursor;
                if (macongty == constant.DAIVIET)
                {
                    objReport.Load_Report(Application.StartupPath + "\\reports\\hoadontienhang_daiviet.rpt", ds);

                    //objReport.Load_SubReport("Sub_BienBanNhap_VTNPL_BTP", objCtrl.LoadPrint_BienBanNhap_L)
                }
                if (macongty == constant.VANXUAN)
                {
                    objReport.Load_Report(Application.StartupPath + "\\reports\\hoadontienhang_vanxuan.rpt", ds);
                }

                DateTime d = context.p_getdate().ElementAt(0).serverdatetime;

                if (d.Day < 10)
                {
                    objReport.Formulas_Report("ngay", "'0" + d.Day.ToString() + "'");
                }
                else
                {
                    objReport.Formulas_Report("ngay", "'" + d.Day.ToString() + "'");
                }
                if (d.Month < 10)
                {
                    objReport.Formulas_Report("thang", "'0" + d.Month.ToString() + "'");
                }
                else
                {
                    objReport.Formulas_Report("thang", "'" + d.Month.ToString() + "'");
                }

                objReport.Formulas_Report("nam", "'" + d.Year.ToString() + "'");


                objReport.Open_Report();
                Cursor.Current = Cursors.Default;
                //objCtrl = Nothing
                //objReport = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void grdata_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dtptungay_ValueChanged(object sender, EventArgs e)
        {
            loaddanhsachhoadontheongay();
        }

        private void dtpdenngay_ValueChanged(object sender, EventArgs e)
        {
            loaddanhsachhoadontheongay();
        }

        

       
    }
}
